<template>
	<view v-if="isLoaded" class="content" :class="{ 'disable-content-bck': isMobileLogin}">
		<!-- 登录按钮 -->
		<view v-if="!isMobileLogin" class="buttons center">
			<!-- #ifdef MP-WEIXIN -->
			<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="btn1 center">
				<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/mobile-icon.png" mode="widthFix"></image>手机号登录
			</button>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<button @click="goMobileLogin()" class="btn1 center">
				<image src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/mobile-icon.png" mode="widthFix"></image>手机号登录
			</button>
			<!-- #endif -->
		</view>
		<popup-agreement ref="pAgreementUser" :agreementMode="0"></popup-agreement>
		<popup-agreement ref="pAgreementPrivate" :agreementMode="1"></popup-agreement>
		
		<!-- 手机号登录弹窗 -->
		<uni-popup ref="pMobile" type="center" mask-background-color="rgba(0,0,0,.65)">
			<view class="mobile-container">
				<view class="mobile-card-group" >
					<view class="mobile-card">
						<view class="center">
							<view class="flex pr-5">
								<image class="mobile-icon" src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/mobile-icon-black.png"
									mode="widthFix">
								</image>
							</view>
							<view>手机号{{isWechatLogin ? '绑定' : '登录'}}</view>
						</view>
						<view class="mobile-input">
							<view class="mobile-input-text center">
								+<text>86</text>
							</view>
							<view class="mobile-input-input">
								<input type="number" v-model="userMoblie" placeholder="请输入手机号" maxlength="11" />
							</view>
						</view>
						<view class="mobile-input">
							<view class="mobile-input-input" style="padding: 0 20px;">
								<input type="number" v-model="smscode" maxlength="6"
									placeholder-style="font-family: Alfa Slab One;font-size: 10px;font-weight: 400;" placeholder="请输入验证码" />
							</view>
							<view @click="doSendSms" class="smscode center">
								<text v-if="smscodeTime === 0" style="color: #83FF23;">获取验证码</text>
								<text v-else style="color: #939393;font-size: 14px;">{{smscodeTime}}秒再次发送</text>
							</view>
						</view>
						<view>
							<button @click="doLogin" class="mobile-login-btn center">{{isWechatLogin ? '绑定' : '登录'}}</button>
						</view>
					</view>
				</view>
				
				<view class="terms safari_only">
					<view class="" @click="isTermsCheck = !isTermsCheck">
						<image style="width: 10px;" src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/radio-icon.png" mode="widthFix"></image>
						<image v-if="isTermsCheck" class="terms-check" src="https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/check.png" mode="widthFix"></image>
					</view>
					<view>
						<text style="margin-left: 5px;">
							登录即表明同意
							<text @click="openAgreement(0)" class="terms-color">用户协议</text>、
							<text @click="openAgreement(1)" class="terms-color">隐私协议</text>
						</text>
					</view>
					
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	const app = getApp()
	export default {
		name: 'index',
		data() {
			return {
				isMobileLogin: false, // 开启手机号登录弹窗
				isWechatLogin: false, // 微信登录成功，绑定手机号模式
				isLoaded: false, // 页面静态资源加载完毕再展示页面
				userMoblie: '', // 手机号
				smscode: '', // 验证码
				smscodeTime: 0, // 是否已发送验证码，倒计时，0可以发送
				isTermsCheck: false,
			}
		},
		async onLoad() {
			// 查看缓存jinxiangguo_login_token
			if (app.globalData.token) {
				uni.redirectTo({
					url: '/pages/game/game'
				})
				return
			}
			
			// #ifdef H5
			// 判断是否在微信客户端
			if (this.$wx && app.isWechat()) {
				let openid = app.getQueryString('openid')
				if (!openid) {
					location.href = app.globalData.requestUrl + '/api/user/wxsnsapi?url=' + (location.origin + location.pathname + (location.search ? location.search : '?1=1'))
					return
				}
				// 拿openid到后台换取token，拿不到就引导用户绑定手机号
				let that = this
				uni.request({
					url: app.globalData.requestUrl + '/api/user/getWxLoginToken',
					method: 'GET',
					data: {
						openid: openid
					},
					success: (res) => {
						console.log(res.data.data)
						if (!res.data.data.token) {
							this.isWechatLogin = true
							this.isMobileLogin = true
							this.$refs.pMobile.open()
							open
						} else {
							uni.setStorage({
								key: 'jinxiangguo_login_token',
								data: res.data.data.token,
								success: function () {
									location.reload()
								}
							})
						}
					},
					complete() {
						that.pageInit() // 加载页面静态资源
					}
				})
			}
			if (!this.isLoaded) {
				await this.pageInit()
			}
			// #endif
			// #ifdef MP-WEIXIN
			this.isLoaded = true
			// #endif
		},
		methods: {
			// #ifdef MP-WEIXIN
			getPhoneNumber (e) {
				console.log(e)
			    if (!e.detail.cloudID) {
			      wx.showToast({
			        title: '登录失败',
			        icon: 'none'
			      })
			      return
			    }
			    let that = this
			    wx.cloud.callFunction({ //连接云函数
			      name:'getPhoneNumber', // 云函数名称
			      data:{
			        weRunData: wx.cloud.CloudID(e.detail.cloudID) // 这个 CloudID 值到云函数端会被替换
			      }
			    }).then(res => {
			      if (!app.globalData.unionid) res.result.unionid
			      uni.request({
			        url: app.globalData.requestUrl + '/api/user/wechat/register',
			        data: {
						unionid: res.result.unionid,
						mobile: res.result.moblie,
						openid: res.result.openid,
			        },
			        method: 'POST',
			        success: function (res2) {
			          let toast = ''
			          console.log(res2.data)
			          app.globalData.token = res2.data.data.token
			          if (res2.data.code === 200) {
			          	uni.showToast({
			          		title: '登录成功！',
			          		icon: 'none'
			          	})
			          	uni.setStorage({
			          		key: 'jinxiangguo_login_token',
			          		data: res2.data.data.token,
			          		success: function () {
			          			uni.reLaunch({
			          				url: '/pages/game/game'
			          			})
			          		}
			          	})
			          } else {
			          	uni.showToast({
			          		title: res2.data.msg,
			          		icon: 'none'
			          	})
			          }
			        },
			        fail: function (res) {
			          wx.showToast({
			            title: '登录失败',
			            icon: 'none'
			          })
			        }
			      })
			      
			    }).catch(err=>{
			      console.log(err)
			    })
			  },
			// #endif
			// #ifdef H5
			async pageInit() {
				await app.preloadImages([
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/TreasureHunter.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/TreasureHunter-white.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/icon.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/star1.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/findjoy.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/bck.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/star2.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/star3.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/star4.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/star5.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/circle.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/logo.png',
					'https://6a69-jinxiangguo-7g6kqddnb0a8aa47-1326817332.tcb.qcloud.la/img/index/mobile-icon.png'
				])
				this.isLoaded = true
				return true
			},
			// #endif
			// 打开用户协议
			openAgreement(mode) {
				app.playAudio()
				if (mode == 0) {
					this.$refs.pAgreementUser.open()
				} else {
					this.$refs.pAgreementPrivate.open()
				}
				
			},
			/**
			 * 打开手机号登录弹窗
			 */
			goMobileLogin() {
				app.playAudio() // 点击音效
				this.isMobileLogin = true
				this.$refs.pMobile.open()
			},
			/**
			 * 执行登录
			 */
			doLogin() {
				app.playAudio() // 点击音效
				if (!this.checkMobile()) return
				if (!this.isTermsCheck) {
					uni.showToast({
						title: '请勾选用户协议',
						icon: 'none'
					})
					return
				}
				// #ifdef H5
				let path = '/api/user/login',
					data = {
						mobile: this.userMoblie,
						code: this.smscode
					}
				// 微信登录后绑定手机号
				if (this.isWechatLogin) {
					data.openid = app.getQueryString('openid')
					path = '/api/user/wxRegister'
				}
				uni.showLoading({
					title: '正在登录'
				})
				uni.request({
					url: app.globalData.requestUrl + path,
					method: 'POST',
					data: data,
					success: (res) => {
						let toast = ''
						console.log(res.data)
						app.globalData.token = res.data.data.token
						if (res.data.code === 200) {
							uni.showToast({
								title: '登录成功！',
								icon: 'none'
							})
							uni.setStorage({
								key: 'jinxiangguo_login_token',
								data: res.data.data.token,
								success: function () {
									location.reload()
								}
							})
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					complete() {
						uni.hideLoading()
					}
				})
				// #endif
			},
			/**
			 * 发送验证码
			 */
			doSendSms() {
				app.playAudio() // 点击音效
				if (!this.checkMobile()) return
				if (this.smscodeTime > 0) return
				uni.request({
				    url: app.globalData.requestUrl + '/api/user/sms', //仅为示例，并非真实接口地址。
					method: 'POST',
				    data: {
				        mobile: this.userMoblie
				    },
				    success: (res) => {
						let toast = ''
						console.log(res.data)
						if (res.data.code === 200) {
							toast = '验证码发送成功'
							this.smscodeTime = 59
							let time = setInterval(() => {
								this.smscodeTime--
								if (this.smscodeTime <= 0) {
									clearInterval(time)
								}
							}, 1000)
						} else {
							toast = '验证码发送失败，请重试'
						}
						uni.showToast({
							title: toast,
							icon: 'none'
						})
				        
				    }
				})
			},
			/**
			 * 验证手机号
			 */
			checkMobile() {
				let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/
				if (!this.userMoblie) { //判断如果手机号为空，提示用户输入手机号
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
					return false
				} else if (!reg.test(this.userMoblie)) { //判断手机号格式时候正确
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return false
				}
				return true
			}
		},
		watch: {}
	}
</script>
<!--这里引入分离的界面样式代码-->
<style scoped>
	@import './index.css';
</style>